<template>
	<view :class="themeName">
		<navbar :title="barTitle"></navbar>
		<view class="community-group-purchase" :style="[infoStyle]">
			<view class="head-icon flex-wrap col--center">
				<view class="white endTime flex row-center col--center">
					<u-icon name="clock-fill" size="40" color="rgba(255, 255, 255, 1)" class="m-r-10" />
					<text>{{$zhTran('距离活动结束还有')}}</text>
					<count-down :time-end="actInfo.end_time2" color="#fff" bgColor="none" separatorColor="#fff"
						fontSize="32" separatorSize="32" class="m-l-10" />
				</view>
				<view class="white text-center m-t-20">{{actInfo.pick_start}}{{$zhTran(' 开始提货')}}</view>
			</view>

			<view class="header u-flex-wrap u-col-top">
				<view class="leader-info p-30 flex">
					<view class="m-r-20">
						<image class="avatar" :src="$getImageUri(leaderInfo.avatar)"></image>
					</view>
					<view class="info">
						<view class="name flex">
							<text>{{leaderInfo.name}}</text>
							<view class="badge m-l-10" :style="{
							backgroundImage: `url(${$getImageUri('resource/image/shopapi/uniapp/leader-badge.png')})`
						}">{{$zhTran('团长')}}</view>
						</view>
						<view>{{$zhTran('联系电话: ')}}{{leaderInfo.phone}}</view>
						<view style="color:rgba(56, 56, 56, 1)">{{$zhTran('提货地址: ')}}{{leaderInfo.region_address}}
						</view>
					</view>
					<view class="change-leader" @tap="toExchange">{{$zhTran('切换团长')}}</view>
				</view>
				<view class="u-border-top p-30 remark" style="width: 100%;">
					{{$zhTran('公告：')}}<text>{{actInfo.explain}}</text>
				</view>
			</view>

			<!-- 商品 -->
			<view :class="['goods-container', `goods-container-${goodsCardStyle}`]">
				<view class="goods-item" v-for="item,idx in goodsList" :key="item.id"
					@click.native="goGoodsDetail(item.goods_id)">
					<goods-card :key="goodsIndex" shape="rectangle" :name="item.goods_name" :image="item.goods_image"
						:contain-style="{ height: '260rpx' }" :fieldShowHide="fieldShowHide"
						:image-style="{ width: '180rpx', height: '180rpx' }">
						<view class="goods-item-price flex-1" slot="default">
							<u-gap height="80"></u-gap>
							<view class="m-t-10 flex row-between">
								<price :content="item.max_price" main-size="42rpx" minor-size="36rpx"
									:prefix="price_symbol"
									:color="fieldStyles.price_color != '' ? fieldStyles.price_color : themeColor">
									<view slot="suffix">
										<price class="muted sm m-l-12" :line-through="true" :prefix="price_symbol"
											:color="fieldStyles.scribing_price_color" slot="suffix"
											:content="item.sell_price"
											v-show="Number(item.sell_price) && fieldShowHide.show_scribing_price" />
									</view>
								</price>
								<view class="number-box u-icon-plus" v-if="buyList[item.item_id] == undefined" :style="{
										background:'rgba(255, 208, 0, 1)',
										borderRadius:'100%',
										height:'60rpx'
									}" @click.native.stop="addGoods(item)">
									<u-icon name="plus" size="26" color="rgba(255, 255, 255, 1)" />
								</view>
								<u-number-box class=" number-box" :index="idx" :disabled-input="true"
									v-model="buyList[item.item_id] " :min="0" bg-color="transparent"
									iconPlusColor="#fff" iconMinusColor="rgba(166, 166, 166, 1)" v-else :diyPlusStyle="{
										bgColor:'rgba(255, 208, 0, 1)',
										color:'rgba(255, 255, 255, 1)',
										borderRadius:'100%',
										inputHeight:60
									}" :diyMinusStyle="{
										borderRadius:'100%',
										inputHeight:60
									}" @change="countChange($event, item.item_id)">
								</u-number-box>
							</view>
						</view>
					</goods-card>
				</view>
			</view>

			<u-gap height="100" v-if="cartLength > 0"></u-gap>

			<!-- 功能按钮组 -->
			<view class="functions" v-if="cartLength > 0">
				<view class="cgp-btns">
					<view class="icon" @click="popCart">
						<u-badge type="error" :count="cartLength" :offset="[-7,-7]"></u-badge>
						<u-image :src="$getImageUri('resource/image/shopapi/uniapp/shopping-basket.png')" width="46rpx"
							height="48rpx"></u-image>
					</view>
					<view class="price flex col-center row-center" v-if="total_amount > 0">
						<price :content="total_amount" main-size="32rpx" minor-size="28rpx" color="#fff"
							:prefix="price_symbol">
							<view slot="suffix" class="muted line-through m-l-20 xxs">
								<price :content="total_reduced" :prefix="$zhTran('已节省 -') + price_symbol"
									:line-through="true" color="rgba(255, 255, 255, 1)" />
							</view>
						</price>
					</view>
					<view class="to-buy flex col--center row-center" @click="toBuy">{{$zhTran('去结算')}}</view>
				</view>
			</view>

			<!-- 页面状态 -->
			<page-status :status="pageStatus">
				<template #error>
					<u-empty :text="$zhTran('社区团购活动异常')"
						:src="$getImageUri('resource/image/shopapi/uniapp/empty/order.png')" :icon-size="280"></u-empty>
				</template>
			</page-status>

			<!-- 加载中 -->
			<u-mask :show="isChangeLoading" :mask-click-able="false" :custom-style="{ background: 'rgba(0, 0, 0, 0)' }">
			</u-mask>
			<view class="loading" v-if="isChangeLoading">
				<u-loading size="40" :color="themeColor"></u-loading>
				<view class="white m-t-20">{{$zhTran(' 加载中... ')}}</view>
			</view>

			<u-popup v-model="cartShow" mode="bottom" border-radius="14">
				<view class="cart-list">
					<view class="cart-header p-30 flex col-top row-between">
						<view class="choose">{{$zhTran('已选产品')}}<text>{{$zhTran('（共'+cartLength+'件）')}}</text></view>
						<view class="clear" @click="clearCart">
							<u-icon name="trash-fill" size="30" color="rgba(166, 166, 166, 1)"
								class="m-r-5" />{{$zhTran('清空')}}
						</view>
					</view>
					<view class="cart-goods p-30">
						<view class="cart-item flex u-border-bottom p-b-30 row-between col--center"
							v-for="item,idx in cartLists" :key="idx">
							<view class="goods-name">{{item.goods.goods_name}}</view>
							<view class="flex">
								<view class="price m-r-20">
									<price :content="item.goods_item.cgp_price" main-size="30rpx" minor-size="26rpx"
										color="rgba(250, 64, 52, 1)" :prefix="price_symbol">
									</price>
								</view>
								<u-number-box class=" number-box" :index="idx" :disabled-input="true" :inputWidth="60"
									v-model="buyList[item.item_id]" :min="0" bg-color="transparent" iconPlusColor="#fff"
									iconMinusColor="rgba(255, 208, 0, 1)" :diyPlusStyle="{
										bgColor:'rgba(255, 208, 0, 1)',
										color:'rgba(255, 255, 255, 1)',
										borderRadius:'100%',
										inputHeight:60
									}" :diyMinusStyle="{
										borderRadius:'100%',
										inputHeight:60,
										border:'1px solid rgba(255, 208, 0, 1)',
									}" @change="countChange($event, item.item_id)">
								</u-number-box>
							</view>
						</view>
					</view>
					<u-gap height="200"></u-gap>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	import {
		apiCommunityGroupPurchaseCartAdd,
		apiCommunityGroupPurchaseCartDel,
		apiCommunityGroupPurchaseCartClear,
		apiCommunityGroupPurchaseCartLists, //商品列表
		apiCommunityGroupPurchaseCartCountChange, //商品数量改变
		apiCommunityGroupPurchaseLeaderDetail,
		apiCommunityGroupPurchaseLeaderActivityDetail,
	} from "@/api/community_group_purchase";
	import {
		PageStatusEnum,
	} from "@/utils/enum";

	export default {
		name: "CGPActivityDetail",

		data() {
			return {
				pageStatus: PageStatusEnum["LOADING"],
				// 页面状态
				actInfo: {}, // 活动信息
				goodsCardStyle: "rectangle", // 商品卡片样式: square -正方形; rectangle -长方形
				price_symbol: '￥',
				goodsList: [],
				buyList: [],
				cartLists: [],
				isChangeLoading: false,
				fieldShowHide: {
					show_goods_model: 0,
					show_goods_stock: 0,
					show_gfa_flag: 0,
					show_goods_code: 0,
					show_goods_tag: 0,
					show_cgp_tag: 1,
					show_scribing_price: 1,
				},
				fieldStyles: {
					price_color: '#FA4034'
				},
				leader_id: '',
				cgp_id: '',
				barTitle: this.$zhTran('社区团购活动'),
				leaderInfo: [],
				total_amount: 0,
				total_reduced: 0,
				cartShow: false
			};
		},

		computed: {
			infoStyle() {
				if (this.actInfo.status == 1) {
					var bgimg = this.$getImageUri('/resource/image/shopapi/default/bg_orange.png')
				} else if (this.actInfo.status == 2) {
					var bgimg = this.$getImageUri('/resource/image/shopapi/default/bg_green.png')
				} else {
					var bgimg = this.$getImageUri('/resource/image/shopapi/default/bg_gray.png')
				}
				return {
					'background-image': `url(${bgimg})`,
				}
			},
			cartLength() {
				return this.cartLists.length
			},
		},

		methods: {
			// 刷新订单数据
			refreshActivityData() {
				return apiCommunityGroupPurchaseLeaderActivityDetail({
						id: this.cgp_id,
					})
					.then((ndata) => {
						let data = this.$zhTran(ndata)
						this.actInfo = data;
						this.goodsList = data.goods ?? []
						this.barTitle = data.name
						return Promise.resolve(data);
					})
					.catch((err) => {
						return Promise.reject(err);
					});
			},
			getLeaderInfo() {
				return apiCommunityGroupPurchaseLeaderDetail({
					leader_id: this.leader_id
				}).then((data) => {
					this.leaderInfo = this.$zhTran(data)
					return Promise.resolve(data);
				}).catch(err => {
					return Promise.reject(err);
				});
			},
			// 跳转商品详情
			goGoodsDetail(goods_id) {
				this.$Router.push({
					path: "/bundle2/pages/community_group_purchase/user/goods_detail",
					query: {
						cgp_id: this.cgp_id,
						goods_id,
						leader_id: this.leader_id
					},
				});
			},

			addGoods(row) {

				if (!this.isLogin) return this.$Router.push("/bundle2/pages/login/login");

				apiCommunityGroupPurchaseCartAdd({
						cgp_id: this.cgp_id,
						leader_id: this.leader_id,
						item_id: row.item_id,
						goods_num: 1,
					})
					.then(() => {
						this.$set(this.buyList, row.item_id, 1)
					})
					.catch((err) => {
						throw new Error(err);
					})
					.finally(() => {
						this.getCartList();
					});
			},

			// 商品数量的修改
			countChange({
				value
			}, item_id) {
				this.isChangeLoading = true;
				if (value > 0) {
					apiCommunityGroupPurchaseCartCountChange({
							cgp_id: this.cgp_id,
							leader_id: this.leader_id,
							item_id: item_id,
							goods_num: value,
						}).then(() => {
							this.$set(this.buyList, item_id, value)
						})
						.finally(() => {
							this.getCartList();
						});
				} else {
					apiCommunityGroupPurchaseCartDel({
							cgp_id: this.cgp_id,
							leader_id: this.leader_id,
							item_id: item_id,
						}).then(() => {
							this.buyList.splice(item_id, 1)
						})
						.finally(() => {
							this.getCartList();
						});
				}
			},
			clearCart() {
				apiCommunityGroupPurchaseCartClear({
						cgp_id: this.cgp_id,
						leader_id: this.leader_id,
					}).then(() => {
						this.buyList = []
					})
					.finally(() => {
						this.getCartList();
					});
			},
			// 获取购物车数据列表
			getCartList() {
				return apiCommunityGroupPurchaseCartLists({
					cgp_id: this.cgp_id,
					leader_id: this.leader_id,
				}).then((res) => {
					this.total_amount = res.total_amount;
					this.total_reduced = res.total_reduced
					this.price_symbol = res.price_symbol;
					this.cartLists = this.$zhTran(res.lists);
					this.isChangeLoading = false;
					this.buyList = [];
					if (this.cartLists.length > 0) {
						this.cartLists.forEach((item) => {
							this.$set(this.buyList, item.item_id, item.goods_num)
						})
					} else {
						this.popCart()
					}
					return Promise.resolve();
				});
			},
			popCart() {
				if (this.cartShow) {
					this.cartShow = false
				} else {
					if (this.cartLength > 0) this.cartShow = true
				}
			},
			toBuy() {
				if (this.cartLength == 0) {
					this.$toast({
						title: this.$zhTran("请添加商品"),
					});
					return
				}
				var that = this
				uni.navigateTo({
					url: "/bundle2/pages/community_group_purchase/order/goods_order",
					events: {
						reCountCarNum(res) {
							that.getCartList();
						}
					},
					success(res) {
						res.eventChannel.emit("receiveData", {
							cgp_id: that.cgp_id,
							leader_id: that.leader_id,
						});
					}
				});
			},
			toExchange() {
				this.$Router.replace({
					path: '/bundle2/pages/community_group_purchase/user/exchange_leader',
					query: {
						cgp_id: this.cgp_id,
						from: 'act_detail',
					},
				});
			}
		},

		async onLoad() {
			const options = this.$Route.query;

			try {
				if (!options.cgp_id) throw new Error(this.$zhTran("社区团购活动异常"));
				this.cgp_id = options.cgp_id;
				this.leader_id = options.leader_id ?? '';
				await this.refreshActivityData()
				await this.getLeaderInfo()

				if (this.leader_id != '')
					await this.getCartList()
				this.pageStatus = PageStatusEnum["NORMAL"];

				if (options.from == 'index') await this.addGoods({
					item_id: options.item_id
				})
			} catch (err) {
				console.log(err);
				this.pageStatus = PageStatusEnum["ERROR"];
			}
		},

		onUnload() {},
	};
</script>

<style lang="scss" scoped>
	.community-group-purchase {
		background-size: 100%;
		background-repeat: no-repeat;
		padding: 30rpx;
		position: relative;

		.head-icon {
			margin: 50rpx 0;

			.endTime {
				font-size: 32rpx;
			}
		}

		.header {
			border-radius: 7px;
			background-color: #FFFFFF;
			display: flex;
			min-height: 264rpx;

			.remark {
				font-size: 24rpx;

				&>text {
					color: rgba(166, 166, 166, 1);
				}
			}

			.leader-info {
				width: 100%;
				background-color: #fff;
				position: relative;
				border-radius: 10rpx;

				.avatar {
					width: 110rpx;
					height: 110rpx;
					border-radius: 50%;
				}

				.info {
					width: calc(100% - 100rpx);
					color: rgba(166, 166, 166, 1);
					font-size: 24rpx;

					&>view {
						margin-bottom: 10rpx;
					}

					.name {
						color: rgba(38, 38, 38, 1);
						font-size: 28rpx;
						font-weight: bold;

						.badge {
							background-repeat: no-repeat;
							background-size: 100% 100%;
							color: #fff;
							padding: 6rpx 15rpx;
							font-size: 22rpx;
						}
					}

				}

				.change-leader {
					background-color: rgba(255, 208, 0, 1);
					color: rgba(74, 25, 0, 1);
					font-size: 24rpx;
					padding: 8rpx 14rpx;
					position: absolute;
					top: 20rpx;
					right: 20rpx;
					border-radius: 4rpx;
				}
			}
		}

		.cgp-share-icon {
			position: absolute;
			top: 30rpx;
			right: 30rpx;
			background-color: rgba(255, 208, 0, 1);
			color: rgba(74, 25, 0, 1);
			font-size: 24rpx;
			padding: 6rpx 20rpx;
			border-radius: 50rpx;
		}


	}

	.goods-container {
		flex: 1;
		display: flex;

		&-square {
			flex-direction: row;
			flex-wrap: wrap;
			justify-content: space-between;
		}

		&-rectangle {
			flex-direction: column;
		}

		.goods-item {
			margin-top: 16rpx;

			.number-box {
				&.u-icon-plus {
					width: 60rpx;
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}
		}
	}

	.functions {
		position: fixed;
		z-index: 9999999;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		height: calc(100rpx + constant(safe-area-inset-bottom));
		height: calc(100rpx + env(safe-area-inset-bottom));
		padding: 0 36rpx constant(safe-area-inset-bottom) 36rpx;
		padding: 0 36rpx env(safe-area-inset-bottom) 36rpx;

		.cgp-btns {
			width: 100%;
			height: 90rpx;
			background-color: rgba(27, 15, 9, 1);
			position: relative;
			border-radius: 0 50rpx 50rpx 0;

			.btn-add {
				position: absolute;
				right: 0;
				top: -120rpx;
			}

			.icon {
				position: absolute;
				left: -16rpx;
				top: -20rpx;
				padding: 30rpx;
				background-color: rgba(255, 208, 0, 1);
				border-radius: 100%;
				border: 10rpx solid rgba(27, 15, 9, 1);
			}

			.price {
				position: absolute;
				left: 126rpx;
				height: 90rpx;
			}

			.to-buy {
				position: absolute;
				right: -1rpx;
				top: 0;
				height: 90rpx;
				padding: 0 30rpx;
				font-size: 28rpx;
				color: rgba(56, 56, 56, 1);
				border-radius: 0 50rpx 50rpx 0;
				background-color: rgba(255, 208, 0, 1);
			}
		}
	}

	.cart-list {
		.cart-header {
			background-color: rgba(248, 248, 250, 1);

			.choose {
				color: rgba(56, 56, 56, 1);
				font-size: 32rpx;
				font-weight: bold;

				&>text {
					color: rgba(166, 166, 166, 1);
					font-size: 24rpx;
					font-weight: normal;
				}
			}

			.clear {
				color: rgba(166, 166, 166, 1);
				font-size: 24rpx;
			}
		}

		.cart-goods {
			max-height: 500rpx;
			overflow: hidden;
			overflow-y: auto;

			.goods-name {
				width: 50%;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				word-break: break-all;
			}

			.price {
				width: 100rpx;
			}
		}
	}
</style>